package design.mode.effective_java.chapter8.item53;

import java.util.*;

/**
 * 返回集合中的最大值-如果为空则抛出异常
 *
 * @author ZhongMingde on 2021/9/1
 */

public class Test1 {
    public static <E extends Comparable<E>> Optional<E> max(Collection<E> c){
        if (c.isEmpty()){
            return Optional.empty();
        }
        E result = null;
        for (E e : c) {
            if (result == null || e.compareTo(result) > 0){

            }
            result = Objects.requireNonNull(e);
        }
        return  Optional.of(result);
    }

    public static <E extends Comparable<E>> Optional<E> max2(Collection<E> c){
        return c.stream().max(Comparator.naturalOrder());
    }

    public static void main(String[] args) {
        Set<String> word = new HashSet<>();
        String lastWordInLexicon = max(word).orElse("No words ");
        String lastWordInLexicon2 = null;
        try {
            lastWordInLexicon2 = max(word).orElseThrow(Exception::new);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String lastWordInLexicon3 = max(word).get();
        System.out.println(lastWordInLexicon3);
    }
 }
